package com.example.myapplication

import com.example.sihookuiklydemo.base.BasePager
import com.example.sihookuiklydemo.base.BasePager.Companion.TITLE_NAME
import com.example.sihookuiklydemo.base.NotifyName
import com.example.sihookuiklydemo.base.setTimeout
import com.example.sihookuiklydemo.bean.CustomDeskModeJson
import com.example.sihookuiklydemo.bean.getDeskModeList
import com.example.sihookuiklydemo.ble.getNewFloatPx
import com.example.sihookuiklydemo.net.Api.Companion.baseUrl
import com.example.sihookuiklydemo.theme.Theme
import com.example.sihookuiklydemo.utils.getLanguage
import com.example.sihookuiklydemo.utils.getShowHeightString
import com.tencent.kuikly.core.base.Animation
import com.tencent.kuikly.core.base.Border
import com.tencent.kuikly.core.base.BorderStyle
import com.tencent.kuikly.core.base.Color
import com.tencent.kuikly.core.base.ComposeView
import com.tencent.kuikly.core.base.ComposeAttr
import com.tencent.kuikly.core.base.ComposeEvent
import com.tencent.kuikly.core.base.Translate
import com.tencent.kuikly.core.base.ViewBuilder
import com.tencent.kuikly.core.base.ViewContainer
import com.tencent.kuikly.core.base.attr.ImageUri
import com.tencent.kuikly.core.base.event.EventHandlerFn
import com.tencent.kuikly.core.directives.vforIndex
import com.tencent.kuikly.core.directives.vif
import com.tencent.kuikly.core.log.KLog
import com.tencent.kuikly.core.module.NetworkModule
import com.tencent.kuikly.core.module.NotifyModule
import com.tencent.kuikly.core.module.RouterModule
import com.tencent.kuikly.core.module.SharedPreferencesModule
import com.tencent.kuikly.core.nvi.serialization.json.JSONArray
import com.tencent.kuikly.core.nvi.serialization.json.JSONObject
import com.tencent.kuikly.core.reactive.handler.observable
import com.tencent.kuikly.core.reactive.handler.observableList
import com.tencent.kuikly.core.views.Image
import com.tencent.kuikly.core.views.ImageView
import com.tencent.kuikly.core.views.List
import com.tencent.kuikly.core.views.ScrollPicker
import com.tencent.kuikly.core.views.Switch
import com.tencent.kuikly.core.views.Text
import com.tencent.kuikly.core.views.View
import com.tencent.kuikly.core.views.compose.Button

internal class DeskModeActionSheetView :
    ComposeView<DeskModeSheetViewAttr, DeskModeActionSheetViewEvent>() {
    companion object {
        var topMargin = 30f
    }

    var animated: Boolean by observable(false)
    private var chooseIdx: Int by observable(0)
    lateinit var theme: Theme
    var didFirstLayout = false
    private var list by observableList<String>()
    var deskModeList by observableList<CustomDeskModeJson>()
    override fun created() {
        super.created()

        var deskModeListString =
            acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)
                .getObject("DeskModeList")
        deskModeListString?.let {
            deskModeList.clear()
            deskModeList.addAll(getDeskModeList(deskModeListString))
        }

        chooseIdx = attr.currentMode
        theme = (getPager() as BasePager).theme
        queryDeskModeList()
    }

    fun queryDeskModeList() {

        var pageJson = pagerData.params
        pageJson?.let {

            var token = it.optString("token")
            var userId = it.optInt("userId")
            var eqId = it.optInt("equipmentId")
            var jsonObject = JSONObject()
            jsonObject.put("equipmentId", eqId)
            jsonObject.put("token", token)
            jsonObject.put("userId", userId)
            var jsonObjectHeader = JSONObject()
            jsonObjectHeader.put("Content-Type", "application/json")
            acquireModule<NetworkModule>(NetworkModule.MODULE_NAME).httpRequest(
                "${baseUrl}app/equipment/info/query",
                true,
                jsonObject,
                headers = jsonObjectHeader,
                responseCallback = { data, success, errorMsg, networkResponse ->
                    var content = data.optJSONObject("content")
                    var code = data.optInt("code")
                    if (code == 0) {
                        content?.let {
                            deskModeList.clear()
                            KLog.i("content", "queryDeskModeList:$it ")
                            acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)
                                .setObject("DeskModeList", content)
                            deskModeList.addAll(getDeskModeList(it))

                        }
                    }

                    KLog.i("ss", "${data.toString()} $success $errorMsg $networkResponse")
                })
        }

    }

    override fun createEvent(): DeskModeActionSheetViewEvent {
        return DeskModeActionSheetViewEvent()
    }

    override fun createAttr(): DeskModeSheetViewAttr {
        return DeskModeSheetViewAttr()
    }

    override fun body(): ViewBuilder {
        val ctx = this
        return {
            attr {
                absolutePosition(0f, 0f, 0f, 0f)
                justifyContentFlexEnd()
                if (ctx.animated) {
                    backgroundColor(Color(0, 0, 0, 0.5f))
                } else {
                    backgroundColor(Color(0, 0, 0, 0f))
                }
                animation(Animation.springEaseIn(0.5f, 0.92f, 1f), ctx.animated)


            }
            event {
                click {
                    ctx.animated = false
                }
                animationCompletion {
                    if (!ctx.animated) {
                        KLog.i("ActionSheetView", "animationCompletion $it")
                        ctx.event.cancelClickHandler?.invoke()
                    }
                }
            }
            View {
                View {
                    attr {

                        alignSelfCenter()
                        backgroundColor(0xffe0e2e7)
                        size(40f, 3f)
                        marginTop(6f)
                        borderRadius(3f)
                    }
                }
                event {
                    click { }
                }
                attr {
                    height(520f)
                    backgroundColor((getPager() as BasePager).theme.colors.background)
                    paddingBottom(30f)
                    borderRadius(16f, 16f, 0f, 0f)
                    if (ctx.animated) {
                        transform(Translate(0f, 0f))
                    } else {
                        transform(Translate(0f, 1f))
                    }
                    animation(Animation.springEaseIn(0.5f, 0.92f, 1f), ctx.animated)
                }
                Text {
                    attr {
                        text(getLanguage("desk_change_mode", "切换模式"))
                        fontSize(getNewFloatPx(16f))
                        marginTop(getNewFloatPx(16f))
                        alignSelfCenter()
                        color((getPager() as BasePager).theme.colors.mainTextColor)

                        useDpFontSizeDim(true)
                    }
                }

                List {
                    attr {
                        flex(1f)
                    }
                    vforIndex({ ctx.deskModeList }) { item, index, _ ->
                        View {
                            attr {
                                marginLeft(24f)
                                marginRight(24f)
                                marginTop(18f)
                                width(ctx.pagerData.pageViewWidth - 48f)

                            }
                            Text {
                                attr {
                                    var showName = if (item.isAuto == true) getLanguage(
                                        "desk_auto_mode",
                                        "智能模式"
                                    ) else item.name
                                    color((getPager() as BasePager).theme.colors.mainTextColor)

                                    text(showName ?: "")
                                    fontSize(17f)
                                    useDpFontSizeDim(true)
                                }
                            }
                            event {
                                click {
                                    ctx.chooseIdx = index
                                    ctx.animated = false
                                    ctx.event.confirmClickHandler?.invoke(item, index)
                                }
                            }
                            View {
                                vif({ ctx.chooseIdx == index }) {
                                    Image {
                                        attr {
                                            src(ImageUri.commonAssets("home_choice.png"))
                                            size(72f, 72f)
                                            resizeStretch()
                                            positionAbsolute()
                                            right(4f)
                                            top(4f)
                                        }
                                    }
                                }

                                attr {
                                    marginTop(4f)
                                    flexDirectionColumn()
                                    width(ctx.pagerData.pageViewWidth - 48f)
                                    /* size(
                                         ctx.pagerData.pageViewWidth - 48f,
                                         if (item.isAuto == true) getNewFloatPx(160f) else getNewFloatPx(
                                             150f
                                         )
                                     )*/
                                    backgroundColor(ctx.theme.colors.grey_1a)
                                    borderRadius(20f)
                                    if (ctx.chooseIdx == index) {
                                        border(
                                            Border(
                                                1f,
                                                BorderStyle.SOLID,
                                                Color(0xffFF3D00)
                                            )
                                        )
                                    }


                                }
                                apply(ctx.tipsView(item))
                                View {
                                    attr {
                                        flexDirectionRow()
                                        justifyContentSpaceEvenly()

                                    }
                                    apply(
                                        ctx.getModeItem(
                                            ImageUri.commonAssets("sittingposture_1_nobg.png"),
                                            item.isAuto!!, item.sit!!
                                        )
                                    )
                                    apply(ctx.getViewLine(item))
                                    apply(
                                        ctx.getModeItem(
                                            ImageUri.commonAssets("sittingposture_2_nobg.png"),
                                            item.isAuto!!, item.stand!!
                                        )
                                    )
                                    apply(ctx.getViewLine(item))
                                    apply(
                                        ctx.getModeItem(
                                            ImageUri.commonAssets("sittingposture_3_nobg.png"),
                                            item.isAuto!!, item.custom!!
                                        )
                                    )

                                }


                            }

                        }


                    }
                }
                Image {
                    attr {
                        size(36f, 36f)
                        src(ImageUri.commonAssets("desk_home_set.png"))
                        positionAbsolute()
                        right(24f)
                        top(12f)
                    }
                    event {
                        click {
                            ctx.pagerData.params.put(
                                TITLE_NAME,
                                getLanguage("desk_mode_setting", "模式设置")
                            )
                            ctx.acquireModule<RouterModule>(RouterModule.MODULE_NAME)
                                .openPage("ModeSetting", ctx.pagerData.params)
                            setTimeout(800) {
                                ctx.animated = false
                            }

                        }
                    }
                }

            }


        }
    }

    fun tipsView(item: CustomDeskModeJson): ViewBuilder {
        return {
            vif({ item.isAuto }) {
                View {
                    attr {
                        minHeight(48f)
                        width(220f)
                        backgroundColor(Color.parseString16ToLong("0xffFF3D00"))
                        borderRadius(20f, 0f, 0f, 20f)
                    }

                    Text {
                        attr {
                            text(
                                getLanguage(
                                    "desk_auto_mode_tips",
                                    "西昊根据人体工程学数据为您推荐的专属高度"
                                )
                            )
                            fontSize(getNewFloatPx(15f))
                            margin(left = 12f, right = 8f, top = 8f, bottom = 8f)
                            useDpFontSizeDim(true)
                            color(Color.WHITE)
                        }

                    }
                }
            }
        }
    }

    //分割线
    fun getViewLine(item: CustomDeskModeJson): ViewBuilder {
        return {
            View {
                attr {

                        marginTop(if (item.isAuto == true) 16f else 56f)

                    /*if (item.isAuto == true) {
                        marginTop(getNewFloatPx(topMargin))
                    }*/
                    backgroundColor((getPager() as BasePager).theme.colors.grey_2)
                    size(1f, getNewFloatPx(60f))
                }
            }
        }
    }

    //高度item
    fun getModeItem(uri: ImageUri, isAuto: Boolean, showValue: Int): ViewBuilder {
        return {
            View {
                attr {
                    marginTop(if (isAuto) 0f else 48f)
                    allCenter()
                }
                Image {
                    attr {

                        size(getNewFloatPx(60f), getNewFloatPx(60f))
                        src(uri)
                    }
                }
                Text {
                    attr {
                        useDpFontSizeDim(true)
                        color(0xff98A2AC)
                        marginTop(8f)
                        marginBottom(16f)
                        fontSize(13f)
                        textAlignCenter()
                        maxWidth(100f)
                        var showText=getShowHeightString(showValue,pagerData.params.optInt(NotifyName.HEIGHT_UNIT))
                        text("${showText}")
                        alignSelfCenter()
                    }
                }

            }
        }
    }

    override fun viewDidLayout() {
        super.viewDidLayout()
        animated = true
    }
}


internal class DeskModeSheetViewAttr : ComposeAttr() {
    var currentMode: Int = 0
    var deskModeList: ArrayList<CustomDeskModeJson>? = null
}

internal class DeskModeActionSheetViewEvent : ComposeEvent() {
    var cancelClickHandler: (() -> Unit)? = null
    var confirmClickHandler: ((customDeskModeJson: CustomDeskModeJson, position: Int) -> Unit)? =
        null

    fun onCancelClick(handler: () -> Unit) {
        cancelClickHandler = handler
    }

    fun onConfirmClick(handler: (customDeskModeJson: CustomDeskModeJson, position: Int) -> Unit) {
        confirmClickHandler = handler
    }
}

internal fun ViewContainer<*, *>.DeskModeActionSheetViewEvent(init: DeskModeActionSheetView.() -> Unit) {
    addChild(DeskModeActionSheetView(), init)
}